import os
import json
import shutil

# 创建一个映射表,将需要替换的字符映射为空字符（''）
trans = str.maketrans(
    {
        "【": "",
        "】": "",
        "《": "",
        "》": "",
        "|": "",
        "｜": "",
        "）": "",
        "（": "",
        "(": "",
        ")": "",
        "{": "",
        "}": "",
        "?": "",
        "[": "",
        "]": "",
        ";": "",
        "#": "",
        "&": "",
        "*": "",
        "@": "",
        "!": "",
        "『": "",
        "』": "",
        "~": "",
        "%": "",
        "^": "",
        "_": "",
        "「": "",
        "」": "",
        "“": "",
        "”": "",
        " ": "",
        ",": "",
        ";": "",
        "/": "",
        "！": "",
        "：": "",
        "，": "",
        "：": "",
        "！":"",
        "？":"",
        "（":"",
        "）":"",
        "——":"",
        "一":"",
        "，":"",
    }
)


def assemble_new_name(file_previous_name):
    # 使用translate方法替换字符
    file_new_name = file_previous_name.translate(trans)
    print("\nFileNewName: ", file_new_name)
    return file_new_name


def get_directory_path(fileAbsolutePath):
    """
    获取文件的所在目录路径
    参数:
    fileAbsolutePath (str): 文件的绝对路径
    返回:
    str: 文件的所在目录路径
    """
    try:
        # 使用 os.path.dirname 获取目录路径
        directory_path = os.path.dirname(fileAbsolutePath)
        return directory_path
    except Exception as e:
        # 捕获并处理异常（虽然 os.path.dirname 很少会抛出异常）
        print(f"\nAn error occurred while obtaining the directory path: {e}")
        return None


def move_file(filePrevPath, destinationPath):
    """
    将文件从源路径移动到目标路径,并包含异常处理
    参数:
    filePrevPath (str): 源文件路径
    destinationPath (str): 目标路径,可以是文件夹或完整的目标文件路径
                           如果是指定文件夹,则保留原文件名;如果是完整路径,则使用指定文件名

    返回: 无返回值
    """
    try:
        # 检查源文件是否存在
        if not os.path.isfile(filePrevPath):
            print(f"Error: Source file does not exist: {filePrevPath}")
            return

        # 如果destinationPath是文件夹,则构建完整的目标文件路径
        if os.path.isdir(destinationPath):
            destinationFile = os.path.join(
                destinationPath, os.path.basename(filePrevPath)
            )
        else:
            # 如果destinationPath是完整路径,则直接使用
            destinationFile = destinationPath
            # 确保目标路径的文件夹存在（如果不存在则创建）
            os.makedirs(os.path.dirname(destinationFile), exist_ok=True)
        # 移动文件
        shutil.move(filePrevPath, destinationFile)
        print(f"The file has been successfully moved to: {destinationFile}")
    except Exception as e:
        # 捕获并处理所有异常
        print(f"An error occurred while moving files: {e}")


def read_json_file_to_dict(jsonFilePath):
    """
    读取指定路径的JSON文件内容,并将其转换为字典

    参数:
    jsonFilePath (str): JSON文件的路径

    返回:
    dict or None: 如果文件存在、内容非空且是有效的JSON格式,则返回转换后的字典;否则返回None
    """
    # 检查文件是否存在
    if not os.path.isfile(jsonFilePath):
        return None

    # 尝试打开并读取文件内容
    try:
        with open(jsonFilePath, "r", encoding="utf-8") as file:
            content = file.read()

        # 检查内容是否为空
        if not content.strip():
            return None

        # 尝试将内容解析为JSON字典
        try:
            data_dict = json.loads(content)
            print("\nDataDict:", data_dict)
            return data_dict
        except json.JSONDecodeError:
            return None
    except Exception as e:
        # 处理其他可能的异常（例如文件读取权限问题）
        print(f"An error occurred while reading the file: {e}")
        return None


def find_file(file_name, folder_path):
    """
    递归查找指定文件夹中的文件
    参数:
    file_name (str): 要查找的文件名
    folder_path (str): 要查找的文件夹路径
    返回:
    str or None: 找到文件的绝对路径或 None
    """
    # 检查传入的文件夹路径是否存在
    if not os.path.isdir(folder_path):
        print("\nFile not found")
        return None

    # 遍历文件夹中的每个条目
    for root, dirs, files in os.walk(folder_path):
        if file_name in files:
            absolute_path = os.path.abspath(os.path.join(root, file_name))
            print(f"\nThe file has been found: {absolute_path}")
            return absolute_path

    return None


def get_video_id(data):
    """从数据字典中获取视频 ID"""
    video_id = str(data.get("bvid", "")).strip()
    if not video_id:
        video_id = str(data.get("avid", "")).strip()
    return video_id


def check_abs_path(video_abs_path, folder_path):
    file_path = "Recording.txt"

    err_content = folder_path + "\t"
    err_content += "Error opening input:No such file or directory"
    success_cont = folder_path + " Successfully"

    if video_abs_path is None:
        # 以追加模式打开文件
        with open(file_path, "a", encoding="utf-8") as file:
            # 写入字符串,并添加换行符(如果需要)
            file.write(err_content + "\n\n")
        print(f"\n0.Appended string to:{file_path}\n")
    else:
        with open(file_path, "a", encoding="utf-8") as file:
            # 写入字符串,并添加换行符(如果需要)
            file.write(success_cont + "\n")
        print(f"\n1.Successfully appended string to:{file_path}\n")


def operation(json_file_name, video_file_name, folder_path, destinationPath):
    json_absolute_path = find_file(json_file_name, folder_path)

    video_absolute_path = find_file(video_file_name, folder_path)
    video_directory_path = get_directory_path(video_absolute_path)

    dict_data = read_json_file_to_dict(json_absolute_path)

    # 获取视频 ID
    video_id = get_video_id(dict_data)

    video_new_name = (
        f"{video_id}-{dict_data['title']}-{dict_data['page_data']['page']}.mp4"
    )
    print("\n", "VideoNewName:", video_new_name)

    video_new_name1 = assemble_new_name(video_new_name)
    video_new_name2 = f"{video_directory_path}{os.sep}{video_new_name1}"

    check_abs_path(video_absolute_path, folder_path)
    # 改名
    move_file(video_absolute_path, video_new_name2)
    # 移动
    move_file(video_new_name2, destinationPath)


def get_first_level_subdirectories(directoryPath):
    """
    获取指定目录下的全部一级子目录的绝对路径集合
    参数:
    directoryPath (str): 指定目录的路径
    返回:
    list: 一级子目录的绝对路径集合
    """
    try:
        # 确保directoryPath是一个存在的目录
        if not os.path.isdir(directoryPath):
            print(f"错误: 目录不存在 - {directoryPath}")
            return []

        # 获取目录下的所有条目（文件和目录）
        entries = os.listdir(directoryPath)

        # 过滤出只有一级子目录，并构建它们的绝对路径
        subdirectories = [
            os.path.join(directoryPath, entry)
            for entry in entries
            if os.path.isdir(os.path.join(directoryPath, entry))
        ]

        return subdirectories
    except Exception as e:
        # 捕获并处理异常
        print(
            f"\nAn error occurred while obtaining the first level subdirectories: {e}"
        )
        return []


def main():
    material_dir = r"C:\sss\paths\666"
    destinationPath = r"C:\sss\paths\999"
    json_file_name = "entry.json"
    video_file_name = "video.m4s"

    subdirs = get_first_level_subdirectories(material_dir)
    for subdir in subdirs:
        print(subdir)
        operation(json_file_name, video_file_name, subdir, destinationPath)


main()
